 
var ImageChooser = function(config){
	this.config = config;
}

ImageChooser.prototype = {
	show : function(el, callback){
		if(!this.win){
			this.initTemplates();

            this.pathTree = new Ext.tree.TreePanel({id:this.config.id+'-tree',
                region: 'center', autoScroll:true, animate:true,
                enableDD:false, containerScroll: true, rootVisible: false, stateful:false,

                loader:new Ext.tree.TreeLoader({dataUrl:this.config.url}),
                root: new Ext.tree.AsyncTreeNode({text:'.',draggable:false,id:'.'}),
				listeners: {
					'click': {fn:this.showDetails, scope:this},
					'dblclick': {fn:this.doCallback, scope:this}
                }
            });
            var treeSort = new Ext.tree.TreeSorter(this.pathTree, {folderSort:true});

			var cfg = {title:'选择图片', id:this.config.id+'-win', layout:'border', minWidth:500, minHeight:300,
				modal:true,closeAction:'hide', border:false,
				items:[this.pathTree,
                    {id:this.config.id+'-dtl', region:'east', split:true,
					width:250,minWidth:200,maxWidth:300
				}],
				buttons: [{id:'ok-btn', text:'确定', handler:this.doCallback, disabled:true, scope:this},
				    {text:'取消',handler:function(){ this.win.hide();},scope: this}],
				keys: { key:27,// Esc key
					handler: function(){ this.win.hide(); },
					scope: this}
			};
			Ext.apply(cfg, this.config);
		    this.win = new Ext.Window(cfg);
            this.callback = callback;
		}
        
	    this.win.show(el);
		this.animateTarget = el;
	},
	
	initTemplates : function(){
		this.detailsTemplate = new Ext.XTemplate(
				'<tpl for=".">',
					'<img border="0" width="250" height="260" src="{url}"/><br/>',
					'<b>文件名:{name}</b>',
				'</tpl>'
		);
		this.detailsTemplate.compile();
	},
	
	showDetails : function(selNode){
	    var detailEl = Ext.getCmp(this.config.id+'-dtl').body;
		if(selNode.leaf && selNode.text.length > 0){
			Ext.getCmp('ok-btn').enable();
            this.selectedNode = selNode;
		    var data = {'url':this.config.imgUrl+selNode.getPath("text"),'name':selNode.id};
            detailEl.hide();
            this.detailsTemplate.overwrite(detailEl, data);
            detailEl.slideIn('l', {stopFx:true,duration:.2});
		} else {
		    Ext.getCmp('ok-btn').disable();
		    detailEl.update('');
		}
	},
	doCallback : function() {
        var selNode = this.selectedNode;
        if (selNode==null || !selNode.leaf) return false;
        var callback = this.callback;
        var pathname = this.config.imgUrl+selNode.getPath("text");
        var filename = selNode.id;
        this.win.hide(this.animateTarget,function(){
            callback(pathname,filename);
        });
    },
	onLoadException : function(v,o){
	    Ext.MessageBox.alert('错误', '数据加载失败！');
	}
};
